/**
 * 今日现货提报页面
 * 王斌
 */
import React, { Component } from 'react';
import {
	StyleSheet, Image, PixelRatio, DeviceEventEmitter,
	Text, View, Dimensions, TouchableOpacity,
	FlatList, Alert
} from "react-native";
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import HTTP from '../../../utils/http'
import Dictionary from '../../../utils/dictionary';
import ToastUtil from '../../../utils/toast';
import { NavigationEvents } from 'react-navigation';
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

export class SpotReportPage extends Component {

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '今日现货提报',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	constructor(props) {
		super(props);
		//goodsCateId = this.props.navigation.state.params.goodsCateId;
		this.state = {
			isLoad: false,   // 是否数据加载完成
			data: [],   // 列表数据存储
			recordCount: 0,   // 数据总条数
			nowList: 0,  // 当前条数
			loadIcon: false,  // 下拉涮新的 图标
			index: 0, // 控制tab选项卡
			corpResult: []
		}
	}

	async componentWillMount () {
		let goodsCateId = '';
		this.pageNo = 1;
		let totalPage = 0;
		this.setState({
			isLoad: true
		});
		this.DictionaryArr = [];

		this._getData(1, true);
		let statusDict = await Dictionary.get('EC_AUDIT_STATUS')
		this.setState({
			corpResult: statusDict
		})
	}

	componentDidMount () {
		DeviceEventEmitter.addListener('getCallBack', (res) => {
			if (res.onoff) {
				this._getData(1, true);
			}
		});
	}


	//tab切换
	_setIndex = (num) => {
		this.setState({
			index: num
		}, function () {
			this._getData(this.pageNo, true);
		});

	}
	//获取数据请求 days: this.state.index == 0 ? 1 : (this.state.index == 1 ? 30 : null)
	async	_getData (pageNo, onrefresh) {
		this.setState({
			loadIcon: true
		})
		let responseData = await HTTP.POST(API_GENERATE(API.PRICE_RECORD), {
			pageNo,
			pageSize: 10,
			//	goodsCateId,
			days: null,
		});
		//responseData = ['1', '2'];
		//alert(JSON.stringify(responseData));
		this.setState({
			loadIcon: false
		});
		totalPage = responseData.totalPage;

		this.setState({
			isLoad: false,
		})

		if (responseData) {
			if (onrefresh) {  // 刷新
				this.setState({
					//isLoad: false,
					data: responseData.rows,
					recordCount: responseData.recordCount,
					nowList: responseData.rows.length
				})
			} else {  // 加载
				this.setState({
					//	isLoad: false,
					data: this.state.data.concat(responseData.rows),
					recordCount: responseData.recordCount,
					nowList: this.state.nowList + responseData.rows.length
				})
			}
		}
	}
	//状态-数据为空
	_emptyFn = () => {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status="empty" emptyText="暂无记录" />
			</View>
		)
	}
	//状态-加载前
	_loadFn = () => {
		return (
			<View style={{ flex: 1 }}>
				<PageStatusIndex status="loading" />
			</View>
		)
	}

	//状态-获取到数据
	_bodyFn = () => {

		let { recordCount, nowList, index, data } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={() => { this._getData(1, true) }} />
				<View style={styles.listBox}>
					{data.length > 0 ? this._renderData() : <PageStatusIndex status="empty" emptyText="暂无记录" />}
				</View>
				{
					data.length > 0 ? (<PageStatusIndex status="bottom" recordCount={recordCount} nowList={nowList} />) : null
				}
			</View >
		)
	}
	//list 渲染数据
	_renderData = () => {
		const { data } = this.state;
		return (
			<FlatList
				data={data}
				renderItem={this._renderItemView.bind(this)}
				refreshing={this.state.loadIcon}
				onRefresh={this._isLoadRefresh.bind(this)}
				onEndReachedThreshold={0.8}
				onEndReached={() => { this._loadData() }}
			/>
		);
	}

	//跳转今日现货提报页面
	_goDetail = (applyId, goodsCateId, goodsId, goodsName, status, branchId, yesdayPrice) => {
		this.props.navigation.navigate('SiterRecordPage', {
			applyId, goodsCateId, goodsId, goodsName, status, branchId, yesdayPrice
		})
	}

	_goDetailShow = (applyId, goodsCateId, goodsId, goodsName, status, branchId) => {
		//ApprovalPage/SiterRecordPage
		let paramsData = { applyId, goodsCateId, goodsId, goodsName, status, branchId };
		this.props.navigation.navigate('PriceApprovalDetailShowPage', {
			paramsData
		})
	}

	_goHistory = (applyId, goodsCateId, goodsId, goodsName, status, branchId) => {
		//ApprovalPage/SiterRecordPage
		let paramsData = {
			applyId, goodsCateId, goodsId, goodsName, status, branchId,
		}
		this.props.navigation.navigate('HistoryPricePage', {
			paramsData
		})
	}

	//提报撤回
	async _priceCancel (applyId) {
		let responseData = await HTTP.POST(API_GENERATE(API.PRICE_CANCEL), { businessKey: applyId });
		console.log('提报撤回:', responseData);
		if (responseData) {
			ToastUtil.showSuccess('价格提报撤回成功!');
			this.setState({
				isLoad: true
			});
			this._getData(1, true);
		} else {
			ToastUtil.showError('价格提报撤回失败');
			this.setState({
				isLoad: true
			});
			this._getData(1, true);
		}
	}

	//一条数据模板
	_renderItemView = (customer) => {
		const { branchId, goodsId, applyId, goodsName, midMarketPrice, yesdayPrice, updateTime, originPrice, status, statusName,
			suggestedPrice, staffName, organName, auditRemark, finalPrice, goodsCateId, createBy, createTime, bizStaffName, lastPrice } = customer.item;

		let downImg = require('../../../imgs/my-siter/down.png');
		let upImg = require('../../../imgs/my-siter/up.png');
		let adjustRange = (suggestedPrice || 0) - (lastPrice || 0)
		if (applyId) {
			return (

				<View style={styles.list}>
					<TouchableOpacity onPress={() => { this._goDetailShow(applyId, goodsCateId, goodsId, goodsName, status, branchId) }}
						activeOpacity={0.5} >
						<View style={styles.listUp}>
							<Text style={[styles.listTitle, { width: 300 * scale }]} numberOfLines={1} ellipsizeMode='tail'>商品:{goodsName}</Text>
							<Text style={styles.statusText}>{statusName}</Text>
						</View>
						<View style={[styles.listDown, styles.listMrigin]}>
							<Text style={styles.listText}>今日提报价: <Text style={styles.themColor}>￥{this.simpleFormatAsMoney(suggestedPrice)}</Text></Text>
							<View style={styles.listInner}>
								<Text style={styles.text}>
									幅度:
						<Text style={{ color: adjustRange >= 0 ? style.color.lightRed : style.color.lightBlue }}>{Math.abs(adjustRange) || '0'}</Text>
								</Text>
								<Image source={adjustRange >= 0 ? upImg : downImg} style={{ marginLeft: 5 * scale }} />
							</View>
						</View>
						<View style={[styles.listDown, styles.borderStart]}>
							<Text style={styles.listText}>上次现货价: ￥{this.simpleFormatAsMoney(lastPrice) || 0.00}</Text>
							{/*<Text style={styles.listText}>市场价: ￥{this.simpleFormatAsMoney(midMarketPrice)}</Text>*/}
						</View>
						<View style={[styles.listDown, styles.borderEnd, styles.borderBot]}>
							<Text style={styles.listText}>提报人: {bizStaffName}</Text>
							<Text style={styles.listText}>提报时间: {createTime}</Text>
						</View>
					</TouchableOpacity>
					<View>
						<View style={styles.largeBtnCell}>
							<View >
								{status && status && ('WAIT_AUDITING' == status || 'AUDITING' == status) ? <TouchableOpacity activeOpacity={0.5} style={[styles.largeBtn, styles.anSe, styles.mgiRight]} onPress={() => {
									Alert.alert('提示', '您确定要撤回该现货价提报吗？', [
										{
											text: '取消',
										}, {
											text: '确定',
											onPress: () => {
												this._priceCancel(applyId);
											}
										}
									]);

								}}>
									<Text style={styles.anSeText}>撤回</Text>
								</TouchableOpacity> : null}
							</View>
							<View >
								{status && 'WAIT_SUBMIT' != status ? <TouchableOpacity activeOpacity={0.5} style={[styles.largeBtn, styles.anSe, styles.mgiRight]} onPress={() => { this._goHistory(applyId, goodsCateId, goodsId, goodsName, status, branchId) }}>
									<Text style={styles.anSeText}>提报历史</Text>
								</TouchableOpacity> : null}
							</View>
							<View >
								{status && 'AUDITING' == status ? null : <TouchableOpacity onPress={() => { this._goDetail(applyId, goodsCateId, goodsId, goodsName, status, branchId, lastPrice) }}
									activeOpacity={0.5} style={[styles.largeBtn, styles.liangSe]}>
									<Text style={styles.liangSeText}>提报</Text>
								</TouchableOpacity>}
							</View>
						</View>
					</View >
				</View >

			)
		} else {
			return (

				<View style={styles.list}>
					<View style={styles.listUp}>
						<Text style={[styles.listTitle, { width: 300 * scale }]} numberOfLines={1} ellipsizeMode='tail'>商品:{goodsName}</Text>
						<Text style={styles.statusText}>{statusName}</Text>
					</View>
					<View style={[styles.listDown, styles.listMrigin]}>
						<Text style={styles.listText}>今日提报价: <Text style={styles.themColor}>￥{this.simpleFormatAsMoney(suggestedPrice)}</Text></Text>
						<View style={styles.listInner}>
							<Text style={styles.text}>
								幅度:
						<Text style={{ color: adjustRange >= 0 ? style.color.lightRed : style.color.lightBlue }}>{Math.abs(adjustRange) || '0'}</Text>
							</Text>
							<Image source={adjustRange >= 0 ? upImg : downImg} style={{ marginLeft: 5 * scale }} />
						</View>
					</View>
					<View style={[styles.listDown, styles.borderStart]}>
						<Text style={styles.listText}>上次现货价: ￥{this.simpleFormatAsMoney(lastPrice)}</Text>
						{/*<Text style={styles.listText}>市场价: ￥{this.simpleFormatAsMoney(midMarketPrice)}</Text>*/}
					</View>
					<View style={[styles.listDown, styles.borderEnd, styles.borderBot]}>
						<Text style={styles.listText}>提报人: {bizStaffName}</Text>
						<Text style={styles.listText}>提报时间: {createTime}</Text>
					</View>
					<View>
						<View style={styles.largeBtnCell}>
							<View >
								{status && ('WAIT_AUDITING' == status || 'AUDITING' == status) ? <TouchableOpacity activeOpacity={0.5} style={[styles.largeBtn, styles.anSe, styles.mgiRight]} onPress={() => {
									Alert.alert('提示', '您确定要撤回该现货价提报吗？', [
										{
											text: '取消',
										}, {
											text: '确定',
											onPress: () => {
												this._priceCancel(applyId);
											}
										}
									]);

								}}>
									<Text style={styles.anSeText}>撤回</Text>
								</TouchableOpacity> : null}
							</View>
							<View >
								{status && 'WAIT_SUBMIT' != status ? <TouchableOpacity activeOpacity={0.5} style={[styles.largeBtn, styles.anSe, styles.mgiRight]} onPress={() => { this._goHistory(applyId, goodsCateId, goodsId, goodsName, status, branchId) }}>
									<Text style={styles.anSeText}>提报历史</Text>
								</TouchableOpacity> : null}
							</View>
							<View >
								{status && 'AUDITING' == status ? null : <TouchableOpacity onPress={() => { this._goDetail(applyId, goodsCateId, goodsId, goodsName, status, branchId, yesdayPrice) }}
									activeOpacity={0.5} style={[styles.largeBtn, styles.liangSe]}>
									<Text style={styles.liangSeText}>提报</Text>
								</TouchableOpacity>}
							</View>
						</View>
					</View >
				</View >
			)
		}
	}
	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this._getData(this.pageNo, true);
	}
	// 上拉加载
	_loadData () {
		if (totalPage > this.pageNo) {
			this.pageNo++;
			this._getData(this.pageNo, false);
		}
	}


	render () {
		let { isLoad } = this.state;
		if (isLoad) {
			return this._loadFn();
		} else {
			return this._bodyFn();
		}
	}

	_getTimeStr (str) {
		if (str && str.length) {
			const currDate = new Date(str.replace(/-/g, '/'));
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate(),
				h = currDate.getHours(),
				mi = currDate.getMinutes();
			let dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
			return dateStr;
		} else {
			return null;
		}
	}

	simpleFormatAsMoney (mnt) {
		// mnt -= 0;
		mnt = mnt ? (Math.round(mnt * 100)) / 100 : undefined;
		return (mnt == Math.floor(mnt)) ? mnt + '.00' : ((mnt * 10 == Math.floor(mnt * 10)) ? mnt + '0' : mnt);
	}

}



const styles = StyleSheet.create({
	largeBtnCell: {
		flexDirection: 'row',
		width: 363 * scale,
		height: 60 * scale,
		justifyContent: 'flex-end',
		alignItems: 'center',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
		backgroundColor: '#fff',
		marginRight: 12 * scale,
	},
	largeBtn: {
		flexDirection: 'row',
		width: 86 * scale,
		height: 34 * scale,
		borderRadius: 60,
		justifyContent: 'center',
		alignItems: 'center',
	},
	largeBtnText: {
		fontSize: 13 * scale,
		color: '#fff'
	},
	statusText: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
	},
	text: {
		fontSize: 13 * scale,
		color: '#404040'
	},
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	listBox: {
		flex: 1,
		backgroundColor: '#F5F5F5',
		paddingBottom: 40 * scale,
	},
	list: {
		backgroundColor: style.color.white,
		marginTop: 12 * scale
	},
	listUp: {
		height: 44 * scale,
		width: 351 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		marginLeft: 12 * scale,
		//mrginRight: 12 * scale,
	},
	listDown: {
		//marginTop: 16 * scale,
		//paddingLeft: 12 * scale,
		//paddingRight: 12 * scale,
		width: 351 * scale,
		marginLeft: 12 * scale,
		flexDirection: 'row',
	}, listMrigin: {
		marginTop: 12 * scale,
	},
	borderStart: {
		marginTop: 4 * scale,
		//paddingBottom: 12 * scale,
	}, borderEnd: {
		marginTop: 4 * scale,
		paddingBottom: 12 * scale,
	}, borderBot: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
	},
	listDownTe: {
		marginBottom: 16 * scale,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		flexDirection: 'row',
	},
	listTitle: {
		fontSize: 14 * scale,
		color: style.color.dark
	},
	listTime: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	nowBottom: {
		position: 'absolute',
		bottom: 0,
		height: 40 * scale,
		width: '100%',
		backgroundColor: style.color.white,
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
	},
	nowBottomText: {
		textAlign: 'center',
		lineHeight: 40 * scale,
		fontSize: 12 * scale,
		color: style.color.dark
	},
	themColor: {
		color: style.color.themeColor
	},
	listText: {
		width: '50%',
		color: style.color.normal,
		fontSize: 12 * scale,
		height: 17 * scale,
	},
	listInner: {
		width: '50%',
		flexDirection: 'row',
		alignItems: 'center'
	},



	tabBox: {
		height: 40 * scale,
		backgroundColor: style.color.white,
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
	},
	chartBox: {
		marginTop: 20 * scale,
	},
	tab: {
		position: 'absolute',
		width: '100%',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-around'
	},
	tabNav: {
		paddingLeft: 20 * scale,
		paddingRight: 20 * scale,
	},
	tabNavActive: {
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderBottomColor: style.color.themeColor,
	},
	tabNavText: {
		lineHeight: 38 * scale
	}, anSe: {
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#4B4B4B',
	}, anSeText: {
		fontSize: 13 * scale,
		color: '#4B4B4B',
	}, liangSe: {
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#2F7BFF',
	}, liangSeText: {
		fontSize: 13 * scale,
		color: '#2F7BFF',
	}, mgiRight: {
		marginRight: 7 * scale,
	}
})
